import Vue from "vue";
export function isArray<T>(arr: any): arr is Array<T> {
  return Array.isArray(arr);
}

export function isString(str: any): str is string {
  return Object.prototype.toString.call(str) === "[object String]";
}

export function isNumber(num: any): num is number {
  return Object.prototype.toString.call(num) === "[object Number]";
}

export function isObject(obj: any): obj is object {
  return Object.prototype.toString.call(obj) === "[object Object]";
}

export function addUnit(unit: string | number, isToPX: boolean = true): string {
  const unitStr: string = String(unit);

  if (unitStr.includes("%")) {
    return unitStr;
  }

  return isToPX ? uni.upx2px(Number(unit)) + "px" : Number(unit) + "px";
}

export function getRect(
  vm: Vue,
  selector: string,
  all: boolean = false
): Promise<any> {
  return new Promise((resolve) => {
    const query = uni.createSelectorQuery().in(vm);
    query[all ? "selectAll" : "select"](selector)
      .boundingClientRect((rect) => {
        if (all && Array.isArray(rect) && rect.length) {
          resolve(rect);
        }
        if (!all && rect) {
          resolve(rect);
        }
      })
      .exec();
  });
}
